package io.yuncheng.modules.sys.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yuncheng.common.annotation.SysLog;
import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.exception.RRException;
import io.yuncheng.common.utils.*;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.yuncheng.common.utils.*;
import io.yuncheng.common.utils.DateUtils;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


/**
 * 密评以及风评方案
 *
 * @author jared
 * @email 15721509625@163.com
 * @date 2020-10-28 19:48:45
 */
@RestController
@Api(tags = "密评管理-split")
@RequestMapping("sys/subappassessmentsplit")
public class SubAppAssessmentSplitController {
    @Autowired
    private SubAppAssessmentSplitService subAppAssessmentSplitService;
    @Autowired
    private SubApplicationService applicationService;
    @Autowired
    private SubAppAssessmentSplitConfigService subAppAssessmentSplitConfigService;
    @Autowired
    private DictConfig dictConfig;
    @Resource
    private SysOperationLogService sysOperationLogService;
    @Resource
    private SysDeptService sysDeptService;

    /**
     * 列表
     */
    @PostMapping("/list")
    @RequiresPermissions("sys:subappassessmentsplit:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = subAppAssessmentSplitService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:subappassessmentsplit:info")
    public R info(@PathVariable("id") Long id){
        SubAppAssessmentSplitEntity subAppAssessmentSplit = subAppAssessmentSplitService.getById(id);

        return R.ok().put("subAppAssessmentSplit", subAppAssessmentSplit);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("sys:subappassessmentsplit:save")
    public R save(@RequestBody SubAppAssessmentSplitEntity subAppAssessmentSplit){
        subAppAssessmentSplitService.save(subAppAssessmentSplit);

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation("更新")
    @PostMapping("/update")
    @RequiresPermissions("sys:subappassessmentsplit:update")
    public R update(@RequestBody SubAppAssessmentSplitEntity subAppAssessmentSplit){
        subAppAssessmentSplitService.updateById(subAppAssessmentSplit);

        return R.ok();
    }

    /**
     * 删除
     */

    @PostMapping("/delete")
    @RequiresPermissions("sys:subappassessmentsplit:delete")
    public R delete(@RequestBody Long[] ids){
        subAppAssessmentSplitService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }
    @ApiOperation("下载")
    @GetMapping(value = "/download/{id}")
    public void logDownload(@PathVariable String id, HttpServletResponse response) throws Exception {
        SubAppAssessmentSplitEntity subAppAssessment = subAppAssessmentSplitService.getById(id);
        List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.queryListByEntityAll(subAppAssessment.getAppId(), subAppAssessment.getAssessmentDate());
        SubApplicationEntity byId = applicationService.getById(subAppAssessment.getAppId());
       new FileUtil().downloadByData(response,list, byId.getAppName() +"-"+ io.yuncheng.common.utils.DateUtils.formatYear(subAppAssessment.getAssessmentDate())+dictConfig.getSysDict(SysDictConstant.ASSESSMENT_TYPE,subAppAssessment.getAssessmentType()+"").getValue()+ "登记方案.xls" );
    }
    @ApiOperation("下载模板")
    @GetMapping(value = "/download/template")
    public void logDownload(HttpServletResponse response) throws Exception {
        FileUtil.downLoadFile(response,"./template/import_template.xlsx");
    }
    /**
     * 修改
     */
    @ApiOperation("确认导入")
    @SysLog("密评登记")
    @PostMapping("/confirmImport")
    public R confirmImport(String uuid) {
        QueryWrapper<SubAppAssessmentSplitEntity> sub = new QueryWrapper<>();
        SubAppAssessmentSplitEntity entity = new SubAppAssessmentSplitEntity();
        entity.setUniqueId(uuid);
        sub.setEntity(entity);
        List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.list(sub);
        SubAppAssessmentSplitEntity entitySp = new SubAppAssessmentSplitEntity();
        entitySp.setAppId(list.get(0).getAppId());
        entitySp.setAssessmentDate(list.get(0).getAssessmentDate());
         Boolean notHasData = subAppAssessmentSplitService.notHasData(entitySp.getAppId(),null);
        Integer windInteger  = Constant.AssessmentTypeEnum.WIND.getValue();
        if(notHasData){
            windInteger = Constant.AssessmentTypeEnum.CONFIDENTIAL.getValue();
        }
        for (SubAppAssessmentSplitEntity appAssessmentSplitEntity : list) {
            appAssessmentSplitEntity.setStatus(Constant.StatusType.NORMAL.getValue());
            appAssessmentSplitEntity.setAssessmentType(windInteger);
        }
       Boolean currentNotHasData = subAppAssessmentSplitService.notHasData(entitySp.getAppId(), entitySp.getAssessmentDate());
        if(!currentNotHasData){
            throw new RRException("已经有其他导入数据被确认");
        }
        for (SubAppAssessmentSplitEntity subAppAssessmentSplitEntity : list) {
            subAppAssessmentSplitService.saveOrUpdate(subAppAssessmentSplitEntity);
        }

        //判定历史是否已经导入判定是风评还是密评
        SysDictEntity sysDict = dictConfig.getSysDict(SysDictConstant.ASSESSMENT_TYPE, windInteger + "");
        Long appId = entitySp.getAppId();
        SubApplicationEntity byId = applicationService.getById(appId);
        SysDeptEntity byId1 = sysDeptService.getById(byId.getDeptId());
        sysOperationLogService.saveLog(LogTypeConstant.ASSESSMENT,"登记 "+ byId1.getName() +" "+ DateUtils.formatYear(entitySp.getAssessmentDate())+ "年" + sysDict.getValue() + "报告");


        return R.ok();
    }



    /**
     * 修改
     */
    @ApiOperation("根据uuid查询信息-待导入的信息")
    @PostMapping("/info/by-uuid")
    public R infoByUid(String uuid) {
        QueryWrapper<SubAppAssessmentSplitEntity> sub = new QueryWrapper<>();
        SubAppAssessmentSplitEntity entity = new SubAppAssessmentSplitEntity();
        sub.orderByAsc("split_type_three");
        entity.setUniqueId(uuid);
        sub.setEntity(entity);
        List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.list(sub);
        return R.ok().put("data",list);
    }
    @ApiOperation("查询对象信息")
    @PostMapping("/info/by-year-deptId")
    public R byYearDeptId(Integer year, Long deptId){
        List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.queryListByDeptYear(deptId, year, Constant.StatusType.NORMAL.getValue());
        return R.ok().put("data",list);
    }
    @ApiOperation("查询对象汇总")
    @PostMapping("/info/dept-sum-total")
    public R upload(Long deptId){
        List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.queryListByDeptYear(deptId, null, Constant.StatusType.NORMAL.getValue());
        Map<Date, SubAppAssessmentSplitEntity> year = list.stream().collect(Collectors.toMap(a -> a.getAssessmentDate(), a -> a, (k1, k2) -> k1,LinkedHashMap::new));
        Map<String, Integer> sumList = list.stream().collect(Collectors.groupingBy(SubAppAssessmentSplitEntity::getSplitTypeDescTwo,Collectors.summingInt(SubAppAssessmentSplitEntity::buildConform)));
        R r = R.ok();
        r.put("year",year);
        r.put("sum",sumList);
        return r;
    }
    @ApiOperation("上传")
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, Integer year, Long deptId){
        Date date = new Date(year - 1900, 0, 1);
        if (file.isEmpty()) {
            return R.error("上传文件不能为空");
        }
        if(deptId == null){
            return R.error("请选择应用登记密评");

        }
        SubApplicationEntity appId = applicationService.queryByDeptId(deptId);
        if (appId == null) {
            return R.error("请选择应用登记密评");
        }
        //省级
        sysDeptService.checkByParentDeptId(appId.getParentDeptId(),"应用登记！");
        QueryWrapper<SubAppAssessmentSplitConfigEntity> sub = new QueryWrapper<>();
        SubAppAssessmentSplitConfigEntity entity = new SubAppAssessmentSplitConfigEntity();
        entity.setAppLevel(appId.getAppLevel());
        entity.setStatus(Constant.StatusType.NORMAL.getValue());
        sub.setEntity(entity);
        List<SubAppAssessmentSplitConfigEntity> configEntities = subAppAssessmentSplitConfigService.list(sub);
        //判定是否已经导入
        List<SubAppAssessmentSplitEntity> splitEntities = subAppAssessmentSplitService.queryListByDeptYear(deptId, year, Constant.StatusType.NORMAL.getValue());
        if(!ObjectUtils.isEmpty(splitEntities)){
            return R.error("数据已经导入");
        }

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String filePath = FileUtil.saveFile(file, uuid);
        SubAppAssessmentSplitEntity subSplit = new SubAppAssessmentSplitEntity();
        subSplit.setFilePath(filePath);
        subSplit.setAssessmentDate(date);
        subSplit.setUniqueId(uuid);
        subSplit.setAppId(appId.getAppId());
        subSplit.setAppLevel(appId.getAppLevel());

        List<SubAppAssessmentSplitEntity> list = null;
        try {
            list = ImportUtil.buildByImportList(file.getInputStream(),configEntities,subSplit,dictConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (SubAppAssessmentSplitEntity subAppAssessmentSplitEntity : list) {
            subAppAssessmentSplitService.save(subAppAssessmentSplitEntity);
        }
        return R.ok().put("uuid",uuid);
    }

}
